package org.sagitta.httprpc;

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sagitta.httprpc.utils.CommonUtil;

public class WebController {
	private static final Log log = LogFactory.getLog(WebController.class);

	private String packageName;
	private Map<String, MappedController> controllers;
	private boolean initialized = false;

	private WebController() {
		controllers = new HashMap<String, MappedController>();
	}

	public static WebController newInstance() {
		return new WebController();
	}

	public void initializeControllerPackage(String packageName) throws JAXBException {
		if (!initialized) {
			this.packageName = packageName;
			initialized = true;
		}
	}
	
	private MappedController getController(String name) throws Exception {
		synchronized (this) {
			MappedController controller = controllers.get(name);
			if (controller == null) {
				log.info("Found the controller for " + name);
				controller = new MappedController();
				controller.initializeController(this.packageName, CommonUtil.upperFirstLetter(name));
				controllers.put(name, controller);
			}
			return controller;
		}
	}

	public WebAction getWebAction(String controllerName, String actionName) throws Exception {
		MappedController controller = getController(controllerName);
		return controller.getAction(actionName);
	}
}
